package com.xneure.code.msg;

import java.util.Iterator;

public class MessageListenerEntry<TMsg> implements Iterator<MessageListener<? super TMsg>>{
	private MessageListener<? super TMsg> msgListener;
	private MessageListenerEntry<TMsg> nextEntry;
	private MessageListenerEntry<TMsg> currEntry;

	public MessageListenerEntry(MessageListener<? super TMsg> ml){
		this.msgListener = ml;
	}

	public void addListener(MessageListener<? super TMsg> ml){
		if(null != nextEntry){
			if(ml != nextEntry.msgListener){
				nextEntry.addListener(ml);
			}
		}else{
			synchronized(msgListener){
				if(null == nextEntry){
					nextEntry = new MessageListenerEntry<TMsg>(ml);
				}else{
					if(ml != nextEntry.msgListener){
						nextEntry.addListener(ml);
					}
				}
			}
		}
	}

	public MessageListener<? super TMsg> getMsgListener(){
		return msgListener;
	}

	public MessageListenerEntry<TMsg> getNextEntry(){
		return nextEntry;
	}

	public void handler(TMsg msg,Enum<?> action){
		msgListener.transmitState = true;
		msgListener.handler(msg,action);
		if(msgListener.isTransmit() && null != nextEntry){
			nextEntry.handler(msg,action);
		}
	}

	@SuppressWarnings({"rawtypes","unchecked"})
	public void updataListener(MessageListenerEntry m1,MessageListener<? super TMsg> msg){
		this.msgListener = msg;
		this.nextEntry = m1;
	}

	@Override
	public boolean hasNext(){
		if(currEntry == null){
			return null != msgListener;
		}else{
			return null != currEntry.nextEntry;
		}
	}

	@Override
	public MessageListener<? super TMsg> next(){
		if(null == currEntry){
			currEntry = this;
		}else{
			currEntry = currEntry.nextEntry;
		}
		return currEntry.msgListener;
	}

	@Override
	public void remove(){
	}
}
